//
//  HomeUnitRecordViewController.m
//  ZJControlsClass
//
//  Created by apple on 2024/10/28.
//

#import "HomeUnitRecordViewController.h"
#import "RegistrationAgreementViewController.h"

#import "HomeAddGoodsTableViewCell.h"
#import "ZJPublicFormAreatTableViewCell.h"
#import "ZJPublicFormTableViewCell.h"
#import "ZJPublicUploadPhotoTableViewCell.h"
#import "HomeUploadFileTableViewCell.h"

#import "HomeNetWorking.h"
#import "HomeUnitModel.h"
#import "TZImagePickerController.h"
#import "HomeGetDetailAllModel.h"
#import "HomeMySlipleModel.h"
#import "ZJPendApprovalDictModel.h"

// 弹出框
#import "SaTMNewUIPickerAlertView.h"
#import "SexAlertView.h"
#import "AreaAlertView.h"
#import "HomePersonAlertView.h"
#import "JWAddressPickerView.h" // 地址选择器
#import "StarTimeAlertView.h"
#import "AlertControllAlertView.h"




@interface HomeUnitRecordViewController ()<UITableViewDelegate,UITableViewDataSource,TZImagePickerControllerDelegate,protocolChangeRegisXieyiTypeDelegate,UITextFieldDelegate,UIDocumentPickerDelegate>{
    NSInteger goodsHei;
}

@property (nonatomic,strong) UITableView * tableView;
@property (nonatomic,strong) NSMutableArray * dataSource;
@property (nonatomic,strong) NSMutableArray * photoArr;
@property (nonatomic,strong) UIView * bottomView;
@property (nonatomic,strong) UIButton * quanBtn;
@property (nonatomic,strong) UIButton * xieyiBtn;
@property (nonatomic,strong) UIButton * canleBtn;
@property (nonatomic,strong) UIButton * uploadBtn;

@property (nonatomic,strong) HomeNetWorking * manager;
@property (nonatomic,strong) HomeGetDetailAllNetworking * allManager;
@property (nonatomic,strong) NSMutableArray * allDataSource;

@property (nonatomic,strong) HomeProcessStarNetworking * uploadManager;
@property (nonatomic,strong) HomeUploadFileNetWorking * fileUploadManager;
@property (nonatomic,strong) NSMutableArray * chooseImgArr;

@property (nonatomic,strong) HomeListMySimpleNetworking * simpleManager;
@property (nonatomic,strong) HomeMySlipleModel * simpleModel;



@property (nonatomic,strong) SaTMNewUIPickerAlertView * checkPickerView;
@property (nonatomic,strong) SexAlertView * sexView;
@property (nonatomic,strong) AreaAlertView * areaAlertView;
@property (nonatomic,strong) HomePersonAlertView * personAlertView;
@property (nonatomic,strong) StarTimeAlertView * startTimeAlertView;

@property (nonatomic,strong) HomeListAllSimpleNetWorking * AllSimplemanager;
@property (nonatomic,strong) NSMutableArray * allSimpleArr;

@property (nonatomic,strong) HomeDictDataTypeNetWorking * DictManager;
@property (nonatomic,strong) NSMutableArray * DictArr;
@property (nonatomic,strong) AlertControllAlertView * controllAlertView;
@property (nonatomic,strong) NSString * controllStr;


@property (nonatomic,strong) HomeUploadFileNetWorking *uploadImgManager;

@property (nonatomic,copy) NSString * processDefinitionId;

// 添加属性来记录当前选中的文件cell下标
@property (nonatomic, assign) NSInteger currentFileIndex;



 
// 整合数据
@property (nonatomic,assign) BOOL xieyiBool;
@property (nonatomic,strong) NSMutableArray * AreaUpData;
@property (nonatomic,strong) NSMutableArray * personUpData;


@end

@implementation HomeUnitRecordViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = self.name;
    self.view.backgroundColor = [UIColor whiteColor];
    self.xieyiBool = NO;
    goodsHei = ALIGN_HEIGHT_PT(180);
    
    [self setUpUI];
    [self loadNet];
    [self getDetailAllNet];
    [self getListMySimpleNet];
    [self getAllSimpleNetWorking];
    [self getDictNet];
}


-(void)setUpUI{
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.bottomView];
    [self.bottomView addSubview:self.quanBtn];
    [self.bottomView addSubview:self.xieyiBtn];
    [self.bottomView addSubview:self.canleBtn];
    [self.bottomView addSubview:self.uploadBtn];
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.equalTo(self.view);
        make.bottom.equalTo(self.view).with.offset(-ALIGN_HEIGHT_PT(130));
    }];
    
    [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.equalTo(self.view);
        make.height.equalTo(@(ALIGN_HEIGHT_PT(130)));
    }];
    [self.quanBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.bottomView).with.offset(ALIGN_WIDTH_PT(10));
        make.top.equalTo(self.bottomView).with.offset(ALIGN_HEIGHT_PT(20));
        make.size.equalTo(@(CGSizeMake(ALIGN_WIDTH_PT(14), ALIGN_WIDTH_PT(14))));
    }];
    
    [self.xieyiBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.quanBtn.mas_right).with.offset(ALIGN_WIDTH_PT(5));
        make.centerY.equalTo(self.quanBtn.mas_centerY);
        make.size.equalTo(@(CGSizeMake(ALIGN_WIDTH_PT(300), ALIGN_WIDTH_PT(25))));
    }];
    
    [self.canleBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.quanBtn.mas_left);
        make.top.equalTo(self.quanBtn.mas_bottom).with.offset(ALIGN_HEIGHT_PT(20));
        make.size.equalTo(@(CGSizeMake((SCREEN_WIDTH - 30) / 2, ALIGN_HEIGHT_PT(45))));
    }];
    
    [self.uploadBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.bottomView).with.offset(-ALIGN_WIDTH_PT(10));
        make.centerY.equalTo(self.canleBtn.mas_centerY);
        make.size.equalTo(@(CGSizeMake((SCREEN_WIDTH - 30) / 2, ALIGN_HEIGHT_PT(45))));
    }];
    
    
}


#pragma mark -- 网络请求
-(void)loadNet{
    
    MBProgressHUD * hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.label.text = @"加载中...";
    
    NSDictionary * dic = @{@"moduleId":self.moduleId};
    [self.manager dispatchTaskWithParam:dic completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
        [hud hideAnimated:YES];
        
        if (responseObject && [responseObject[@"code"] integerValue] == 200) {
                       
            self.processDefinitionId = responseObject[@"data"][@"processDefinitionId"];
            
            
            NSData *jsonData = [responseObject[@"data"][@"formItems"] dataUsingEncoding:NSUTF8StringEncoding];
            NSError *error;
            NSArray *array = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];
            NSLog(@"=====-----%@",array);
            if (error) {
                NSLog(@"JSON解析出错：%@", error);
                [LUtilityTools showAlertWithTitle:@"温馨提示" message:[NSString stringWithFormat:@"JSON解析出错：%@", error] buttonAction:^{
                    
                }];
                
                return;
            }

            [self.dataSource addObjectsFromArray:[HomeUnitModel mj_objectArrayWithKeyValuesArray:array]];
//            NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

            [self.dataSource enumerateObjectsUsingBlock:^(HomeUnitModel * obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if ([obj.name isEqualToString:@"currentOrgName"]){
                    obj.props.input = responseObject[@"data"][@"currentOrgName"];
                    obj.props.placeholder = responseObject[@"data"][@"currentOrgName"];
                }
            }];
            
            [self.tableView reloadData];

            
            
        }else{
            [LUtilityTools showAlertWithTitle:@"温馨提示" message:responseObject[@"msg"] buttonAction:^{
                [self.navigationController popViewControllerAnimated:YES];
            }];
        }
    }];
    
}

-(void)getDictNet{
    
    [self.DictManager dispatchTaskWithParam:@{@"type":@"access_control"} completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
        if (responseObject && [responseObject[@"code"] intValue] == 200){
            self.DictArr = [NSMutableArray arrayWithArray:[ZJPendApprovalDictModel mj_objectArrayWithKeyValuesArray:responseObject[@"data"]]];
        }else{
            [LUtilityTools showAlertWithTitle:@"温馨提示" message:responseObject[@"msg"] buttonAction:^{
                
            }];
        }
    }];
    
    
    
}



-(void)getDetailAllNet{
    
    [self.allManager dispatchTaskWithParam:@{} completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
        if (responseObject && [responseObject[@"code"] intValue] == 200){
            
            [self.allDataSource addObjectsFromArray:[HomeGetDetailAllModel mj_objectArrayWithKeyValuesArray:responseObject[@"data"]]];
            [self.tableView reloadData];
            
        }else{
            [LUtilityTools showAlertWithTitle:@"温馨提示" message:responseObject[@"msg"] buttonAction:^{
                
            }];
        }
    }];
    
}

-(void)getListMySimpleNet{ // 获取我的公司下部门精简信息列表
    
    [self.simpleManager dispatchTaskWithParam:@{} completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
        if (responseObject && [responseObject[@"code"] intValue] == 200){
           
            self.simpleModel = [HomeMySlipleModel mj_objectWithKeyValues:responseObject[@"data"]];
       
        }else{
            [LUtilityTools showAlertWithTitle:@"温馨提示" message:responseObject[@"msg"] buttonAction:^{
                
            }];
        }
    }];
    
}



-(void)getAllSimpleNetWorking{
    
    [self.AllSimplemanager dispatchTaskWithParam:@{} completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
        if (responseObject && [responseObject[@"code"] intValue] == 200){
            self.allSimpleArr = [NSMutableArray arrayWithArray:responseObject[@"data"]];
        }else{
            [LUtilityTools showAlertWithTitle:@"温馨提示" message:responseObject[@"msg"] buttonAction:^{
                
            }];
        }
    }];
}


-(void)respondsTo_changeXieyiType:(UIButton *)sender{
    sender.selected = !sender.selected;
    if (sender.selected){
        [self.quanBtn setImage:[UIImage imageNamed:@"勾"] forState:(UIControlStateSelected)];
        self.xieyiBool = YES;
    }else{
        [self.quanBtn setImage:[UIImage imageNamed:@"未选中圆圈"] forState:(UIControlStateNormal)];
        self.xieyiBool = NO;
    }
}


#pragma mark -- 点击事件
-(void)respondsTo_xieyiBtn{
    RegistrationAgreementViewController * vc = [RegistrationAgreementViewController new];
    vc.delegate = self;
    [self.navigationController pushViewController:vc animated:YES];
}



-(void)respondsTo_canleBtn{
    [self.navigationController popViewControllerAnimated:YES];
}
 
// 提交
-(void)respondsTo_uploadBtn{
    
    if (self.xieyiBool == NO){
        [MBProgressHUD showError:@"请阅读《注册协议》"];
        return;
    }
    NSMutableDictionary * paramer = @{}.mutableCopy;
    
    __block BOOL shouldContinue = YES;
    
    // 整合数据
    [self.dataSource enumerateObjectsUsingBlock:^(HomeUnitModel  * obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        if (!shouldContinue) {
            *stop = YES;
            return;
        }
        
        if ([obj.props.required boolValue] == YES) {
            if ([obj.name isEqualToString:@"common_apply_pass_region"] && self.AreaUpData.count == 0) {
                [MBProgressHUD showError:@"请选择通行区域"];
                shouldContinue = NO;
                *stop = YES;
                return;
            }
            
            if ([obj.name isEqualToString:@"common_user_id"] && self.personUpData.count == 0) {
                [MBProgressHUD showError:obj.props.placeholder];
                shouldContinue = NO;
                *stop = YES;
                return;
            }
            
            if ([obj.name isEqualToString:@"common_department_id"] && obj.props.input.length == 0) {
                [MBProgressHUD showError:obj.props.placeholder];
                shouldContinue = NO;
                *stop = YES;
                return;
            }
            
            if ([obj.name isEqualToString:@"personal_leading_people"] && obj.props.input.length == 0) {
                [MBProgressHUD showError:obj.props.placeholder];
                shouldContinue = NO;
                *stop = YES;
                return;
            }
            
            if (([obj.valueType isEqualToString:@"DateRange"] && obj.props.starTime.length == 0 ) || ([obj.valueType isEqualToString:@"Date"] && obj.props.input.length == 0)) {
                [MBProgressHUD showError:obj.props.placeholder];
                shouldContinue = NO;
                *stop = YES;
                return;
            }
            
            if ([obj.name isEqualToString:@"access_control"] && self.controllStr.length == 0) {
                [MBProgressHUD showError:obj.props.placeholder];
                shouldContinue = NO;
                *stop = YES;
                return;
            }
            
            if ([obj.valueType isEqualToString:@"Image"] && !obj.props.url) {
                [MBProgressHUD showError:@"请上传图片"];
                shouldContinue = NO;
                *stop = YES;
                return;
            }
            
            if ([obj.name isEqualToString:@"common_file"] && !obj.props.url) {
                [MBProgressHUD showError:@"请上传文件"];
                shouldContinue = NO;
                *stop = YES;
                return;
            }
            
            if ([obj.valueType isEqualToString:@"String"] || [obj.valueType isEqualToString:@"Select"] || [obj.valueType isEqualToString:@"Textarea"] || [obj.valueType isEqualToString:@"Dict"]) {
                if (obj.props.input.length == 0) {
                    [MBProgressHUD showError:[NSString stringWithFormat:@"%@",obj.props.placeholder]];
                    shouldContinue = NO;
                    *stop = YES;
                    return;
                }
            }
            
            
            
        }
        
        if ([obj.valueType isEqualToString:@"Select"]){ // 判断
            // 通讯区域
            if ([obj.name isEqualToString:@"common_apply_pass_region"]){
                [paramer setValue:[SStringUtils jsonStringWithParameters:self.AreaUpData] forKey:[NSString stringWithFormat:@"%@|%@",obj.name,obj.id]];
            }
            // 选择员工
            if ([obj.name isEqualToString:@"common_user_id"]){
                [paramer setValue:[SStringUtils jsonStringWithParameters:self.personUpData] forKey:[NSString stringWithFormat:@"%@|%@",obj.name,obj.id]];
            }
            
            // 选择部门
            if ([obj.name isEqualToString:@"common_department_id"]){
                
                NSDictionary * dic = @{@"id":obj.id,
                                       @"name":obj.props.input
                };
                [paramer setValue:[SStringUtils jsonStringWithParameters:dic] forKey:[NSString stringWithFormat:@"%@|%@",obj.name,obj.id]];
            }
            // 选择人员
            if ([obj.name isEqualToString:@"personal_leading_people"]) {
                NSArray * dic = @[@{@"id":obj.id,
                                       @"name":obj.props.input
                }];
                [paramer setValue:[SStringUtils jsonStringWithParameters:dic] forKey:[NSString stringWithFormat:@"%@|%@",obj.name,obj.id]];
            }
            
            // 背景审查结果
            if ([obj.name isEqualToString:@"background_review_result"]) {
                [paramer setValue:obj.props.input forKey:[NSString stringWithFormat:@"%@|%@",obj.name,obj.id]];
            }
            
        }else{
            
            if ([obj.valueType isEqualToString:@"DateRange"] || [obj.valueType isEqualToString:@"TimeRange"]){ // 开始时间  结束时间
                NSArray * arr = @[obj.props.starTime,obj.props.endTime];
                [paramer setValue:arr forKey:[NSString stringWithFormat:@"%@|%@",obj.name,obj.id]];
                
            }else{
                [paramer setValue:obj.props.input forKey:[NSString stringWithFormat:@"%@|%@",obj.name,obj.id]];
            }
            
            if ([obj.name isEqualToString:@"access_control"]){ // 通行门禁
                [paramer setValue:self.controllStr forKey:[NSString stringWithFormat:@"%@|%@",obj.name,obj.id]];
            }
            
        }
        
        
        if ([obj.valueType isEqualToString:@"Image"]){
            if(obj.props.url) {
                NSMutableArray * arr = @[].mutableCopy;
                NSDictionary * dic  = @{@"url":[NSString stringWithFormat:@"%@",obj.props.url],
                                        @"name":[NSString stringWithFormat:@"%@",obj.props.filename?obj.props.filename:@""]
                };
                [arr addObject:dic];
                
                [paramer setValue:[SStringUtils jsonStringWithParameters:arr] forKey:[NSString stringWithFormat:@"%@|%@",obj.name,obj.id]];
            }
        }
        
        if ([obj.name isEqualToString:@"common_file"]){ // 文件上传
            if(obj.props.url) {
                NSMutableArray * arr = @[].mutableCopy;
                NSDictionary * dic  = @{@"url":[NSString stringWithFormat:@"%@",obj.props.url],
                                        @"name":[NSString stringWithFormat:@"%@",obj.props.filename?obj.props.filename:@""]
                };
                [arr addObject:dic];
                
                [paramer setValue:[SStringUtils jsonStringWithParameters:arr] forKey:[NSString stringWithFormat:@"%@|%@",obj.name,obj.id]];
            }
        }
        
    }];

    if (shouldContinue) {
        NSMutableDictionary * dic = @{}.mutableCopy;
        [dic setValue:paramer forKey:@"formData"];
        [dic setValue:self.processDefinitionId forKey:@"processDefinitionId"];
        
        MBProgressHUD * hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        hud.label.text = @"正在加载...";
        [hud removeFromSuperViewOnHide];
        
        [self.uploadManager dispatchTaskWithParam:dic completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
            [hud hideAnimated:YES];
            if (responseObject && [responseObject[@"code"] intValue] == 200){
            
                [MBProgressHUD showSuccess:@"提交成功"];
                [self.navigationController popViewControllerAnimated:YES];
                
            }else{
                [LUtilityTools showAlertWithTitle:@"温馨提示" message:responseObject[@"msg"] buttonAction:nil];
            }
            
        }];
    }
    
}


#pragma mark -- UITableViewDelegate,UITableViewDataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataSource.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    HomeUnitModel * model = self.dataSource[indexPath.row];
    if (![model.valueType isEqualToString:@"Image"] && ![model.name isEqualToString:@"common_apply_pass_region"] && ![model.name isEqualToString:@"tool_pass_region"] && ![model.name isEqualToString:@"tool_table"] && ![model.name isEqualToString:@"common_file"]) {
        // 不复用cell,每次创建新的cell
        ZJPublicFormTableViewCell * cell = [[ZJPublicFormTableViewCell alloc]initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:@"ZJPublicFormTableViewCell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.model = model;
        return cell;
        
    }else if ([model.name isEqualToString:@"common_apply_pass_region"] || [model.name isEqualToString:@"tool_pass_region"]){ // 通行区域
        // 不复用cell
        ZJPublicFormAreatTableViewCell * cell = [[ZJPublicFormAreatTableViewCell alloc]initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:@"ZJPublicFormAreatTableViewCell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.model = model;
        return cell;
        
    }else if ([model.name isEqualToString:@"tool_table"]){ // 货物
        // 不复用cell
        HomeAddGoodsTableViewCell * cell = [[HomeAddGoodsTableViewCell alloc]initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:@"HomeAddGoodsTableViewCell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.model = model;
        cell.block = ^(NSInteger hei) {
            self->goodsHei = hei;
            // 使用主线程刷新表格
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView beginUpdates];
                [self.tableView endUpdates];
            });
        };
        return cell;
        
    }else if ([model.name isEqualToString:@"common_file"]){ // 文件上传
        // 不复用cell
        HomeUploadFileTableViewCell * cell = [[HomeUploadFileTableViewCell alloc]initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:@"HomeUploadFileTableViewCell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.model = model;
        return cell;
        
    }else{
        // 不复用cell
        ZJPublicUploadPhotoTableViewCell *cell = [[ZJPublicUploadPhotoTableViewCell alloc]initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:@"ZJPublicUploadPhotoTableViewCell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        if ([model.props.required boolValue] == YES){
            cell.relabel.hidden = NO;
        }else{
            cell.relabel.hidden = YES;
        }
        
        cell.titleLabel.text = model.props.title;
        cell.uploadLabel.text = model.props.placeholder;
        
        if (model.props.url) {
            cell.addImg.hidden = YES;
            cell.uploadLabel.hidden = YES;
            
            [cell.photoImg sd_setImageWithURL:[NSURL URLWithString:model.props.url]];
            
        }else{
            cell.addImg.hidden = NO;
            cell.uploadLabel.hidden = NO;
        }
        
        
        
        return cell;
    }
    
    return [UITableViewCell new];
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    HomeUnitModel * model = self.dataSource[indexPath.row];
    if (![model.valueType isEqualToString:@"Image"]) {
        
        ZJPublicFormTableViewCell * cell = (ZJPublicFormTableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
        
      
        if ([model.name isEqualToString:@"personal_sex"]) { // 选择男女
            
            __weak typeof (self)weakSelf = self;
            weakSelf.sexView = [SexAlertView new];
            weakSelf.sexView.dataSource = [NSMutableArray arrayWithObjects:@"男",@"女", nil];
            weakSelf.sexView.block = ^(NSString * sexStr) {
                
                model.props.input = sexStr;
                cell.inputTextF.text = sexStr;
                
            };
            
            [kWindow addSubview:self.sexView];
            
        }else if ([model.valueType isEqualToString:@"DateRange"] || [model.valueType isEqualToString:@"TimeRange"]){ // 包含开始时间  结束时间
            
            __weak typeof (self)weakSelf  = self;
            weakSelf.startTimeAlertView = [StarTimeAlertView new];
            weakSelf.startTimeAlertView.StartBlock = ^(NSString * star, NSString * end) {
                if (star) {
                    model.props.starTime = [NSString stringWithFormat:@"%@ %@",star,@"00:00:00"];
                    model.props.endTime = [NSString stringWithFormat:@"%@ %@",end,@"23:59:59"];
                    cell.inputTextF.text = [NSString stringWithFormat:@"%@-%@",star,end];
                }
            };
            [kWindow addSubview:weakSelf.startTimeAlertView];
            
        }else if ([model.valueType isEqualToString:@"Date"] || [model.valueType isEqualToString:@"DateTime"] ){ // 出生年月日 || 行截止日期
            
            __weak typeof(self)weakSelf = self;
            weakSelf.checkPickerView = [[SaTMNewUIPickerAlertView alloc]init];
            weakSelf.checkPickerView.block = ^(NSString * timeStr) {
                if (timeStr) {
                    model.props.input = timeStr;
                    cell.inputTextF.text = timeStr;
                }
            };
            [kWindow addSubview:self.checkPickerView];
            
        }else if ([model.name isEqualToString:@"personal_origin"]){ // 选择籍贯
            
            [JWAddressPickerView showWithAddressBlock:^(NSString *province, NSString *city, NSString *area) {
                NSString * addressStr = [NSString stringWithFormat:@"%@-%@-%@",province,city,area];
                model.props.input = addressStr;
                cell.inputTextF.text = addressStr;
            }];
            
            
            
        }else if ([model.name isEqualToString:@"common_apply_pass_region"] || [model.name isEqualToString:@"tool_pass_region"]){
            
                    __weak typeof (self)weakSelf = self;
                    weakSelf.areaAlertView = [AreaAlertView new];
                    weakSelf.areaAlertView.dataSource = [NSMutableArray arrayWithArray:self.allDataSource];
                    weakSelf.areaAlertView.Areablock = ^(NSMutableArray * upArr, NSMutableArray * showArr) {
                        
                        self.AreaUpData = [NSMutableArray arrayWithArray:upArr];
                        NSString * str = [showArr  componentsJoinedByString:@","];
                        model.props.input = str;
                        if (upArr.count > 0){
                            model.props.placeholder = @"";
                        }else{
                            model.props.placeholder = @"请选择区域";
                        }
                        
                        [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:NO];
                    };
                    
                    [kWindow addSubview:self.areaAlertView];
                    
        }else if ([model.name isEqualToString:@"common_user_id"]){ // 选择员工
            
            __weak typeof (self) weakSelf = self;
            weakSelf.personAlertView = [HomePersonAlertView new];
            weakSelf.personAlertView.model = self.simpleModel;
            weakSelf.personAlertView.personBlock = ^(NSMutableArray * upArr, NSMutableArray * showArr) {
                
                self.personUpData = [NSMutableArray arrayWithArray:upArr];
                NSString * str = [showArr componentsJoinedByString:@"-"];
                model.props.input = str;
                cell.inputTextF.text = str;
            };
            
            
            
            [kWindow addSubview:self.personAlertView];
            
        }else if ([model.name isEqualToString:@"common_department_id"]){ // 选择部门
            
            __weak typeof (self)weakSelf = self;
            weakSelf.sexView = [SexAlertView new];
            weakSelf.sexView.TypeBool = YES;
            weakSelf.sexView.dataSource = [NSMutableArray arrayWithArray:self.simpleModel.orgList];
            weakSelf.sexView.block = ^(NSString * sexStr) {
                
                model.props.input = sexStr;
                cell.inputTextF.text = sexStr;
                
            };
            [kWindow addSubview:self.sexView];

            
        }else if ([model.name isEqualToString:@"background_review_result"]){ // 背景审查结果
            
            __weak typeof (self)weakSelf = self;
            weakSelf.sexView = [SexAlertView new];
            weakSelf.sexView.dataSource = [NSMutableArray arrayWithObjects:@"审核通过",@"审核不通过", nil];
            weakSelf.sexView.block = ^(NSString * sexStr) {
                
                model.props.input = sexStr;
                cell.inputTextF.text = sexStr;
                
            };
            
            [kWindow addSubview:self.sexView];

            
        }else if ([model.name isEqualToString:@"common_file"]){ // 文件上传
            // 创建文档选择器实例

            NSArray *documentTypes = @[@"public.data"];
            // 保存当前选中的下标
            self.currentFileIndex = indexPath.row;
            UIDocumentPickerViewController *documentPicker = [[UIDocumentPickerViewController alloc] initWithDocumentTypes:documentTypes inMode:UIDocumentPickerModeImport];
            documentPicker.delegate = self;
            documentPicker.modalPresentationStyle = UIModalPresentationFormSheet;
            [self presentViewController:documentPicker animated:YES completion:nil];
            
            
        }else if ([model.name isEqualToString:@"personal_leading_people"]){ // 引领人
            
            __weak typeof (self)weakSelf = self;
            weakSelf.sexView = [SexAlertView new];
            
            NSMutableArray * simArr = @[].mutableCopy;
            [self.allSimpleArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                [simArr addObject:obj[@"nickname"]];
            }];
            weakSelf.sexView.dataSource = [NSMutableArray arrayWithArray:simArr];
            weakSelf.sexView.block = ^(NSString * sexStr) {
                
                model.props.input = sexStr;
                cell.inputTextF.text = sexStr;
                
            };
            
            [kWindow addSubview:self.sexView];
            
        }else if ([model.name isEqualToString:@"access_control"]){ // 通行门禁
            __weak typeof (self)weakSelf = self;
            weakSelf.controllAlertView = [AlertControllAlertView new];
            weakSelf.controllAlertView.dataSource = [NSMutableArray arrayWithArray:self.DictArr];
            weakSelf.controllAlertView.block = ^(NSString * str) {
                cell.inputTextF.text = str;
                self.controllStr = str;
            };
            [kWindow addSubview:weakSelf.controllAlertView];
            
        }
    
    }else{ // 选择照片
        
        ZJPublicUploadPhotoTableViewCell * cell = (ZJPublicUploadPhotoTableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
        
        TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc]initWithMaxImagesCount:9 columnNumber:4 delegate:self pushPhotoPickerVc:YES];
        //设置目前已经选中的图片数组
        imagePickerVc.allowPickingVideo = NO;
        imagePickerVc.allowTakeVideo = NO;
        imagePickerVc.showSelectedIndex = YES;

        [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
            
            self.photoArr = @[].mutableCopy;
            
            
            [self.photoArr addObjectsFromArray:photos];
            NSString * str = [NSString stringWithFormat:@"%@",[self.photoArr firstObject]];
            if ([str hasPrefix:@"http://"] || [str hasPrefix:@"https://"]) {
                [cell.photoImg sd_setImageWithURL:[NSURL URLWithString:str]];
            }else{
                cell.photoImg.image = [self.photoArr firstObject];
            }
            cell.addImg.hidden = YES;
            cell.uploadLabel.hidden = YES;
            
            NSString * filename = [assets valueForKey:@"filename"];
            
            // 单张图片上传
            [self.fileUploadManager uploadImageWithParam:@{@"filename":filename} sourceImg:[self.photoArr firstObject] completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
                if (responseObject && [responseObject[@"code"] intValue] == 200){
                    
                    NSString * str = [SStringUtils jsonStringWithParameters:responseObject[@"data"]];
                    NSData * dicData = [str dataUsingEncoding:NSUTF8StringEncoding];
                    NSError * dicErr ;
                    NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:dicData options:NSJSONReadingMutableContainers error:&dicErr];
                    model.props.url = dic[@"url"];
                    model.props.filename = dic[@"name"];
                    
                }
            }];
            
        }];
        imagePickerVc.modalPresentationStyle = UIModalPresentationFullScreen;
        [[SaViewControllerUtils currentViewController] presentViewController:imagePickerVc animated:YES completion:nil];
    
    }
    
}





-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    HomeUnitModel * model = self.dataSource[indexPath.row];
    if ([model.valueType isEqualToString:@"Image"]) {
        return ALIGN_HEIGHT_PT(145);
    }else if ([model.name isEqualToString:@"tool_table"]){
        return MAX(goodsHei, ALIGN_HEIGHT_PT(180));
    }else if ([model.name isEqualToString:@"common_file"]){
        return ALIGN_HEIGHT_PT(100);
    }
    else{
        if ([model.name isEqualToString:@"common_apply_pass_region"] || [model.name isEqualToString:@"tool_pass_region"]){
            return [self.tableView cellHeightForIndexPath:indexPath model:model keyPath:@"model" cellClass:[ZJPublicFormAreatTableViewCell class] contentViewWidth:SCREEN_WIDTH / 2 - ALIGN_WIDTH_PT(30)];
        }else{
            return ALIGN_HEIGHT_PT(50);
        }
    }
    return 0;
}

#pragma mark -- UIDocumentPickerDelegate
// 文件选择完成后的处理
- (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentsAtURLs:(NSArray<NSURL *> *)urls {
    NSURL *selectedFileURL = urls.firstObject;
    // 获取文件数据
    NSData *fileData = [NSData dataWithContentsOfURL:selectedFileURL];
    
    // 创建请求体
    NSString *boundary = [NSString stringWithFormat:@"Boundary-%@", [[NSUUID UUID] UUIDString]];
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
    
    NSMutableData *body = [NSMutableData data];
    
    // 添加文件数据
    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"file\"; filename=\"%@\"\r\n", selectedFileURL.lastPathComponent] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:fileData];
    [body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    
    // 结束标记
    [body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    
    // 创建请求
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString:@"http://test.sczhbf.com:58088/app-api/infra/file/uploadDetail"]];
    [request setHTTPMethod:@"POST"];
    [request setValue:contentType forHTTPHeaderField:@"Content-Type"];
    [request setValue:@"1" forHTTPHeaderField:@"Tenant-Id"];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [request setValue:[defaults valueForKey:@"accessToken"] forHTTPHeaderField:@"Authorization"];
    [request setHTTPBody:body];
    
    // 发起上传请求
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (error) {
            NSLog(@"上传失败:%@", error);
            dispatch_async(dispatch_get_main_queue(), ^{
                [MBProgressHUD showError:@"上传失败"];
            });
            return;
        }
        
        NSError *jsonError;
        NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonError];
        
        if (jsonError) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [MBProgressHUD showError:@"解析响应失败"];
            });
            return;
        }
        
        if ([responseDict[@"code"] intValue] == 200) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [MBProgressHUD showSuccess:@"上传成功"];
                
                // 更新对应下标的model
                HomeUnitModel *model = self.dataSource[self.currentFileIndex];
                model.props.url = responseDict[@"data"][@"url"];
                model.props.filename = responseDict[@"data"][@"name"];

                // 刷新对应的cell
                NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.currentFileIndex inSection:0];
                HomeUploadFileTableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
                [cell.fileBtn setTitle:responseDict[@"data"][@"name"] forState:UIControlStateNormal];
                
                
                
                
            });
        } else {
            dispatch_async(dispatch_get_main_queue(), ^{
                [MBProgressHUD showError:responseDict[@"msg"] ?: @"上传失败"];
            });
        }
    }];
    [task resume];
}



- (void)documentPickerWasCancelled:(UIDocumentPickerViewController *)controller {
    // 用户取消选择时的处理逻辑
    NSLog(@"取消选择文件");
}



-(void)changeRegisXieyiType{
    [self.quanBtn setImage:[UIImage imageNamed:@"勾"] forState:(UIControlStateNormal)];
    self.xieyiBool = YES;
}



#pragma mark -- 懒加载
-(UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectZero style:(UITableViewStylePlain)];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _tableView;
}
-(UIView *)bottomView{
    if (!_bottomView) {
        _bottomView = [UIView new];
        _bottomView.backgroundColor = [UIColor whiteColor];
    }
    return _bottomView;
}

-(UIButton *)quanBtn{
    if (!_quanBtn) {
        _quanBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
        [_quanBtn setImage:[UIImage imageNamed:@"未选中圆圈"] forState:(UIControlStateNormal)];
        [_quanBtn setImage:[UIImage imageNamed:@"勾"] forState:(UIControlStateSelected)];
        [_quanBtn addTarget:self action:@selector(respondsTo_changeXieyiType:) forControlEvents:(UIControlEventTouchUpInside)];
    }
    return _quanBtn;
}
-(UIButton *)xieyiBtn{
    if (!_xieyiBtn) {
        _xieyiBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
        NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:@"我已经阅读《用户申请协议》"];
        [attributedString addAttribute:NSForegroundColorAttributeName
                                 value:COLOR_RGB(50, 113, 237)
                               range:NSMakeRange(5, 8)];
        [_xieyiBtn setAttributedTitle:attributedString forState:UIControlStateNormal];
        _xieyiBtn.titleLabel.font = FONT12;
        _xieyiBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        [_xieyiBtn addTarget:self action:@selector(respondsTo_xieyiBtn) forControlEvents:UIControlEventTouchUpInside];
    }
    return _xieyiBtn;
}

-(UIButton *)canleBtn{
    if (!_canleBtn) {
        _canleBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
        [_canleBtn setTitle:@"取消" forState:UIControlStateNormal];
        [_canleBtn setTitleColor:COLOR_RGB(50, 113, 237) forState:UIControlStateNormal];
        _canleBtn.titleLabel.font = FONT16;
        _canleBtn.layer.cornerRadius = 10;
        _canleBtn.layer.masksToBounds = YES;
        _canleBtn.layer.borderColor = COLOR_RGB(50, 113, 237).CGColor;
        _canleBtn.layer.borderWidth = 0.5;
        [_canleBtn addTarget:self action:@selector(respondsTo_canleBtn) forControlEvents:UIControlEventTouchUpInside];
    }
    return _canleBtn;
}

-(UIButton *)uploadBtn{
    if (!_uploadBtn) {
        _uploadBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
        [_uploadBtn setTitle:@"提交" forState:UIControlStateNormal];
        [_uploadBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _uploadBtn.backgroundColor = COLOR_RGB(50, 113, 237);
        _uploadBtn.titleLabel.font = FONT16;
        _uploadBtn.layer.cornerRadius = 10;
        _uploadBtn.layer.masksToBounds = YES;
        [_uploadBtn addTarget:self action:@selector(respondsTo_uploadBtn) forControlEvents:UIControlEventTouchUpInside];
    }
    return _uploadBtn;
}


-(HomeNetWorking *)manager{
    if (!_manager) {
        _manager = [HomeNetWorking new];
    }
    return _manager;
}
-(HomeGetDetailAllNetworking *)allManager{
    if (!_allManager){
        _allManager = [HomeGetDetailAllNetworking new];
    }
    return _allManager;
}


-(HomeProcessStarNetworking *)uploadManager{
    if (!_uploadManager){
        _uploadManager = [HomeProcessStarNetworking new];
    }
    return _uploadManager;
}

-(HomeUploadFileNetWorking *)fileUploadManager{
    if (!_fileUploadManager){
        _fileUploadManager = [HomeUploadFileNetWorking new];
    }
    return _fileUploadManager;
}

-(HomeListMySimpleNetworking *)simpleManager{
    if (!_simpleManager){
        _simpleManager = [HomeListMySimpleNetworking new];
    }
    return _simpleManager;
}


-(HomeListAllSimpleNetWorking *)AllSimplemanager{
    if (!_AllSimplemanager){
        _AllSimplemanager = [HomeListAllSimpleNetWorking new];
    }
    return _AllSimplemanager;
}

-(HomeDictDataTypeNetWorking *)DictManager{
    if (!_DictManager){
        _DictManager = [HomeDictDataTypeNetWorking new];
    }
    return _DictManager;
}



-(HomeUploadFileNetWorking *)uploadImgManager{
    if (!_uploadImgManager){
        _uploadImgManager = [HomeUploadFileNetWorking new];
    }
    return _uploadImgManager;
}



-(NSMutableArray *)dataSource{
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}
-(NSMutableArray *)allDataSource{
    if (!_allDataSource){
        _allDataSource = [NSMutableArray array];
    }
    return _allDataSource;
}




@end
